package com.rran.study.chat.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.rran.study.chat.server.cache.LocalCache;
import com.rran.study.chat.server.core.repository.ChannelResponsitory;
import com.rran.study.chat.server.dto.request.GroupChatMsg;
import com.rran.study.chat.server.dto.request.SingleMsg;
import com.rran.study.chat.server.core.repository.ChannelFactory;
import com.rran.study.chat.server.service.ChatService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @author yy
 * @Type SingleChatService.java
 * @Desc
 * @date 2020/8/9 18:51
 */
@Service
public class ChatServiceImpl implements ChatService {

    @Override
    public void singleChat(SingleMsg msg) {
        String target = msg.getTarget();
        ChannelHandlerContext channel = ChannelFactory.getChannelHandlerContext(target);
        try {
            channel.channel().writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(msg)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void groupChat(GroupChatMsg msg) {
        String groupId = msg.getGroupId();
        Set<String> groupMembers = LocalCache.getMembers(groupId);
        Set<ChannelHandlerContext> ctxs = ChannelResponsitory.getChannelHandlerContexts(groupMembers);
        try {
            for (ChannelHandlerContext context : ctxs) {
                context.writeAndFlush(msg.getTime() + "  " + msg.getUserName() + "说:" + msg.getContext());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
